import React, { useEffect, useState } from 'react';
import { Avatar, List, Typography } from 'antd';
import { fetchDatabases } from '@/service/api';
import { getLogos } from '@/store/slice/app';
const { Text } = Typography;

interface DatabaseProps {
  onDatabaseChanged: (database: Bn.Meta.MetaDatabase) => void;
}

const DatabaseList = ({ onDatabaseChanged }: DatabaseProps) => {
  const logos = useAppSelector(getLogos);
  const [data, setData] = useState<Bn.Meta.MetaDatabase[]>([]);
  const [currentItem, setCurrentItem] = useState<Bn.Meta.MetaDatabase>();

  const handleItemClick = (item: Bn.Meta.MetaDatabase) => {
    setCurrentItem(item);
    onDatabaseChanged(item);
  }

  useEffect(() => {
    (async () => {
      let databases = (await fetchDatabases()).data;
      if (databases === null) {
        databases = [] as Bn.Meta.MetaDatabase[];
      }
      setData(databases);
      if (databases.length > 0) {
        // 默认选中第一条
        handleItemClick(databases[0]);
      }
    })();
  }, []);

  return (
    <List
      size="large"
      dataSource={data}
      renderItem={(item, index) => (
        <List.Item
          key={item.id}
          onClick={() => handleItemClick(item)}
          style={{backgroundColor: currentItem?.id == item.id ? '#f0f0ff' : 'white'}}
        >
          <List.Item.Meta
            avatar={
              <Avatar
                shape="square"
                size={'large'}
                src={logos[item.dbType]}
              />
            }
            title={<Text strong>{item.friendlyName}</Text>}
            description={
              <Text color="secondary">
                {item.hostName}:{item.port}
              </Text>
            }
          />
        </List.Item>
      )}
    />
  );
}

export default DatabaseList;

// ## index_definition_list
// #if(${$hasPk})
//     INDEX ${tableName}_pkey (
//     #foreach(${col} in ${table.columns})
//         #if(${col.isPk}==true)
//             ,${col.columnName}
//         #end
//     #end
//     )
// #end

// #set($hasPk = false)

// ## column_definition_list
// #foreach(${col} in ${table.columns})
//     ${col.columnName}

//     #if(${col.isPk}==true)
//         #set($hasPk=true)
//     #end
// #end
